<template>
	<view class="container">
		<view class="carousel" v-if="product.imgs.length>0">
			<swiper indicator-dots circular=true duration="400">
				<swiper-item class="swiper-item" v-for="(item,index) in product.imgs" :key="index">
					<view class="image-wrapper">
						<image :src="item.url" class="loaded" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="title-section">
			<text class="title">{{product.name}}</text>
			<view class="price-box">
				<text class="price text-red">¥{{product.price}}</text>
				<text class="m-price text-gray">{{product.originalPrice}}</text>
				<text class="fr text-gray">销量: {{product.virtualSales}}</text>
			</view>
		</view>

		<view class="cu-list menu margin-bottom-xl">
			<view class="cu-item arrow" @click="this.isShowSpeAttr=!this.isShowSpeAttr">
				<text>产品规格</text>
				<text class="text-gray">{{selectSku.select?selectSku.title:"请选择产品规格"}}</text>
			</view>
			<view class="cu-item arrow" @click="this.loadCoupon();this.isShowCoupon=!this.isShowCoupon">
				<text>优惠卷</text>
				<text class="text-gray">请领取优惠卷</text>
			</view>
			<view class="cu-item arrow" v-if="freight" @click="this.isShowCitys=!this.isShowCitys">
				<text style="min-width:80rpx;">运费</text>
				<view class="margin-top-10">
					<view v-if="freight.isFree">
						<view class="text-gray">全国包邮</view>
					</view>
					<view v-else>
						<picker mode="multiSelector" :range="citys" range-key="name" @columnchange="changeCity" @change="chooseCity">
							<text class="text-gray">配送至:{{freight.city}}</text>
							<text class="text-gray margin-left-10">
								<text v-if="!freight.isCondition">首{{freight.firstCount}}运费{{freight.firstPrice}}，每增加{{freight.nextCount}}增加运费¥{{freight.nextPrice}}</text>
								<text v-else>单笔购买满{{freight.condition}}免邮费</text>
							</text>
						</picker>
					</view>
				</view>
			</view>
		</view>

		<view class="remark-section">
			<scroll-view class="bg-gray nav text-center">
				<view class="flex text-center">
					<view class="cu-item flex-sub" :class="0==currentTab?'text-white cur':''" @click="tabSelect" :data-id="0">图文详情</view>
					<view class="cu-item flex-sub" :class="1==currentTab?'text-white cur':''" @click="tabSelect" :data-id="1">产品参数</view>
					<view class="cu-item flex-sub" :class="2==currentTab?'text-white cur':''" @click="tabSelect" :data-id="2">买家评论({{comments.length}})</view>
				</view>
			</scroll-view>
			<swiper :current="currentTab" @change="swiperChange" :style="{height:swiperHeight+'px'}">
				<swiper-item>
					<view class="remark-content" :id="'swiper_id_1'">
						<u-parse :content="product.txt.remark"></u-parse>
					</view>
				</swiper-item>
				<swiper-item>
					<view :id="'swiper_id_2'">
						<view class="cu-list menu margin-bottom-xl">
							<view class="cu-item" v-for="(item,index) in product.attrs" :key="index">
								<text>{{item.name}}:{{item.data}}</text>
							</view>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<view :id="'swiper_id_3'">
						<uni-evaluate :list-data="comments"/>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="cu-bar bg-white tabbar border shop fixed">
			<button class="action" open-type="contact">
				<view class="cuIcon-service text-green"></view>客服
			</button>
			<view class="action text-orange" @click="toFavorite">
				<view :class="isFavorite?'cuIcon-favorfill':'cuIcon-favor'"></view> {{isFavorite?'已收藏':'收藏'}}
			</view>			
			<view class="action" @click="toCart">
				<view class="cuIcon-cart">
					<view class="cu-tag badge" v-if="productCount>0">{{productCount}}</view>
				</view>购物车
			</view>
			<view class="bg-orange submit" @click="addToCart">加入购物车</view>
			<view class="bg-red submit" @click="directBuy">立即订购</view>
		</view>

		<view class="cu-modal bottom-modal" :class="isShowCoupon ? 'show':'hide'" @click="this.isShowCoupon=false">
			<view class="cu-dialog" @click.stop="">
				<view class="coupon-list" v-if="couponList.length>0">
					<view class="coupon-item" v-for="(coupon,index) in couponList" :key="index">
						<view class="con">
							<view class="left">
								<text class="title">满{{coupon.minimums}}元立减<text class="price">{{coupon.discount}}</text>元</text>
								<text class="time">在领取后{{coupon.days}}天内有效。限领{{coupon.limitNum}}张,剩余{{coupon.remaining}}张</text>
							</view>
							<view class="circle l"></view>
							<view class="circle r"></view>
							<button :disabled="coupon.remaining<=0" class="bg-red cu-btn" @click="toReceiveCoupon" :data-value="coupon.id">立即领取</button>
						</view>
						<text class="tips">{{coupon.rangeName}}</text>
					</view>
				</view>
				<view class="padding flex flex-direction" v-if="couponList.length>0">
					<button class="cu-btn round bg-red margin-bottom-50 margin-top-20 lg" @click="this.isShowCoupon=false">关闭</button>
				</view>
				<view v-else class="no_coupon">没有优惠卷哦!</view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="isShowSpeAttr?'show':''" @click="this.isShowSpeAttr=false">
			<view class="cu-dialog" @click.stop="">
				<view class="layer attr-content">
					<view class="a-t">
						<image :src="product.url" />
						<view class="right text-left">
							<text class="price margin-top-50 text-red">¥{{selectSku.price}}</text>
							<view class="selected text-gray" v-if="selectSku.title">
								已选：<text>{{selectSku.title}}</text>
							</view>
						</view>
					</view>
					<view class="text-left oh margin-top-20" v-for="(attr,attrIndex) in product.speAttrs" :key="attrIndex">
						<text>{{attr.name}}</text>
						<view class="oh">
							<view class="fl margin-top-10 margin-bottom-10 margin-right-20" v-for="(item,itemIndex) in attr.data" :key="itemIndex">
							<button class="cu-btn orange block" :class="item.checked?'bg-green':'line-green'" @click="chooseSpeAttr" :data-attr-index="attrIndex" :data-item-index="itemIndex">
									{{item.name}}
								</button>
							</view>
						</view>
					</view>
					<view class="split-line margin-top-20"></view>
					<view class="oh margin-top-50 margin-bottom-20">
						<text class="fl margin-left-20 margin-top-10">购买数量</text>
						<text class="fl margin-left-10 margin-top-20 text-xs text-gray">库存{{selectSku.stock}}件</text>
						<uni-number-box :disabled="!selectSku.select" class="fr step" :min="1" :value="selectSku.buyCount" @change="changeNum"/>
					</view>
					<button :disabled="!selectSku.select" :class="selectSku.select?'round':''" class="btn main-bg-color lg margin-top-100 margin-bottom-50" @click="chooseComplete">完成</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue';
	import uParse from '@/components/u-parse/u-parse.vue';
	import uniEvaluate from '../../components/xiujun-evaluate/uni-evaluate.vue';
	import {ProductService,FreightService,FavoriteService} from "@/api/ProductService.js"
	import {CommentService} from "@/api/MessageService.js"
	import {CouponService} from "@/api/PromotionService.js"
	import {CartService} from "@/api/OrderService.js"
	import {CityService} from "@/api/CommonService.js"
	
	export default {
		components: {uParse,uniEvaluate,uniNumberBox},
		data() {
			return {
				currentTab: 0,isFavorite:false,productCount:0,isAddToCart:undefined,citys: [],
				product: {
					name:undefined,price:0,originalPrice:0,virtualSales:0,
					imgs: [],attrs:[],speAttrs:[],skus:[],txt:{remark:undefined}
				},
				comments:[],
				swiperHeight:0,defaultHeight:0,isShowSpeAttr:false,productId:0,defaultSkuPrice:undefined,
				selectSku:{buyCount:1,sn:undefined, stock:0,title:undefined,price:undefined,value:"",select:false},
				isShowCoupon: false,couponList: [],
				freight:undefined,isShowCitys:false
			};
		},
		onPullDownRefresh() {
			this.initData();
			this.loadProduct();
			this.loadComment();
			this.loadFreight();
			this.loadFavorite();
			this.loadProductCountFromCart();
			uni.stopPullDownRefresh();
		},
		onShareAppMessage: function() {
			uni.showShareMenu({
			  withShareTicket: true,
			  menus: ['shareAppMessage', 'shareTimeline']
			})
		},
		onShareTimeline: function (res) {
		    return {
		      title: this.product.name
		    }
		 },
		created() {
			this.initData();
			uni.getSystemInfo({
				success: (res) => {
					this.defaultHeight=(res.windowHeight * (750 / res.windowWidth));
				}
			});
		},
		onLoad(options) {
			uni.showShareMenu({});
			this.productId=options.productId;
			this.loadCitys();
		},
		onReady() {
			this.loadProduct();
			this.loadComment();
			this.loadFreight();
			this.loadFavorite();
			this.loadProductCountFromCart();
		},
		methods: {
			initData(){
				this.isShowSpeAttr=false;
				this.isShowCoupon=false;
			},
			loadProduct(){
				ProductService.detail(this.productId).then((res)=>{
					this.product=res;
					this.$set(this.product,'txt',res.txt)
					this.setAppTitle();
					this.initSpeAttrValue();
					this.setSwiperHeight();
				});
			},
			setAppTitle(){
				uni.setNavigationBarTitle({
					title:this.product.name
				});
			},
			loadComment(){
				CommentService.listComment(this.productId).then(res=>{
					this.comments=res;
				});
			},
			loadFreight(){
				const that=this;
				uni.getLocation({
				    type: 'wgs84',
				    success: function (res) {
						FreightService.getFreightTitle(that.productId,res.latitude,res.longitude,"","").then(result=>{
							that.freight=result;
						});
				    }
				});
			},
			loadCoupon(){
				CouponService.listAvailableCoupon(this.productId).then(res=>{
					this.couponList=res;
				});
			},
			changeCity(e){
				const column=e.detail.column;
				const value=e.detail.value;
				if(column===0){
					this.$set(this.citys,1,this.citys[0][value].children);
					this.$set(this.citys,2,this.citys[1][0].children);
				}else if(column===1){
					this.$set(this.citys,2,this.citys[1][value].children);
				}
			},
			chooseCity(e){
				const province=this.citys[0][e.detail.value[0]];
				const city=this.citys[1][e.detail.value[1]];
				FreightService.getFreightTitle(this.productId,"","",province.name,city.name).then(result=>{
					this.freight=result;
				});
			},
			initSpeAttrValue(){
				this.product.speAttrs.forEach((attr)=>{
					attr.data.forEach(item=>{
						item.checked=false;
					})
				})
				this.selectSku.stock=this.product.totalStock;
				if(this.product.skus){
					this.product.skus.sort(function(a,b){
						return a.price-b.price;
					});
				}
				const length = this.product.skus.length;
				const minPrice=this.product.skus[0].price;
				const maxPrice=this.product.skus[length-1].price;
				if(parseFloat(minPrice)===parseFloat(maxPrice)){
					this.defaultSkuPrice=minPrice;
				}else{
					this.defaultSkuPrice=minPrice+" - "+maxPrice;
				}
				this.selectSku.price=this.defaultSkuPrice;
			},
			loadCitys(){
				CityService.getCitys(3).then(res=>{
					const province=res;
					this.citys=[[],[],[]];
					this.$set(this.citys,0,res);
					this.$set(this.citys,1,res[0].children);
					this.$set(this.citys,2,res[0].children[0].children);
				});
			},
			toCart(){
				uni.switchTab({url:"/pages/cart/index"});
			},
			addToCart(){
				if(this.selectSku.select){
					const cart={buyCount:this.selectSku.buyCount,sn:this.selectSku.sn,productId:this.productId};
					CartService.addCart(cart).then(()=>{
						this.loadProductCountFromCart();
					});
				}else{
					this.isShowSpeAttr=true;
					this.isAddToCart=true;
				}
			},
			directBuy(){
				if(this.selectSku.select){
					const cart={buyCount:this.selectSku.buyCount,name:this.product.name,price:this.selectSku.price,sn:this.selectSku.sn,productId:this.productId,speTitle:this.selectSku.title,url:this.product.url};
					const that=this;
					uni.navigateTo({
						url:"/pages/cart/confirm",
						success:function(res){
							res.eventChannel.emit('sendProducts', [cart]);
						}
					})
				}else{
					this.isShowSpeAttr=true;
					this.isAddToCart=false;
				}
			},
			chooseComplete(){
				this.isShowSpeAttr=false;
				if(this.isAddToCart){
					this.addToCart();
				}else if(this.isAddToCart===false){
					this.directBuy();
				}
				this.isAddToCart=undefined;
			},
			loadProductCountFromCart(){
				CartService.loadProductCountFromCart().then(res=>{
					this.productCount=parseInt(res);
				});
			},
			loadFavorite(){
				FavoriteService.checkFavorite(this.productId).then(res=>{
					this.isFavorite=res;
				});
			},
			toFavorite(){
				if(this.isFavorite){
					FavoriteService.unFavorite(this.productId).then(()=>{
						this.loadFavorite();
					});
				}else{
					FavoriteService.favorite(this.productId).then(()=>{
						this.loadFavorite();
					});
				}
			},
			toReceiveCoupon(e){
				const couponId=e.currentTarget.dataset.value;
				const that=this;
				CouponService.receiveCoupon(couponId).then(res=>{
					uni.showToast({
						title:"领取成功!",
						success:function(){
							that.loadCoupon();
						}
					});
				});
			},
			tabSelect(e) {
				this.currentTab = e.currentTarget.dataset.id;
			},
			swiperChange(e){
				this.currentTab=e.target.current
				this.setSwiperHeight();
			},
			setSwiperHeight() {
				const that = this;
				setInterval(function(){
					let obj = uni.createSelectorQuery().in(that).select("#swiper_id_" + (that.currentTab+1));
					obj.boundingClientRect(function(data) {
						if (data) {
							that.swiperHeight = data.height;
							if(that.swiperHeight<that.defaultHeight){
								that.swiperHeight=that.defaultHeight;
							}
						}
					}).exec();
				},2000)
			},
			chooseSpeAttr(e) {
				let attrs = this.product.speAttrs;
				let itemIndex = parseInt(e.currentTarget.dataset.itemIndex);
				let attrIndex =parseInt(e.currentTarget.dataset.attrIndex);
				this.product.speAttrs[attrIndex].data.forEach((item,index)=>{
					if(itemIndex!==index){
						item.checked=false;
					}
				});
				this.product.speAttrs[attrIndex].data[itemIndex].checked=!this.product.speAttrs[attrIndex].data[itemIndex].checked;
				const attrValues=[];
				this.selectSku={buyCount:1,sn:undefined,stock:this.product.totalStock,title:undefined,price:this.defaultSkuPrice,value:"",select:false};
				this.product.speAttrs.forEach((attr,index)=>{
					attr.data.forEach(item=>{
						if(item.checked){
							attrValues.push(item.seq);
						}
					});
				});
				this.selectSku.value=attrValues.join(",");
				this.product.skus.forEach(sku=>{
					if(sku.speAttrValue===this.selectSku.value){
						this.selectSku.stock=sku.stock;
						this.selectSku.title=sku.title;
						this.selectSku.price=sku.price;
						this.selectSku.sn=sku.sn;
						this.selectSku.select=true;
					}
				});
			},
			changeNum(e){
				this.selectSku.buyCount=e;
			}
		}
	}
</script>

<style lang='scss'>
	.carousel {
		height: 722upx;
		position: relative;

		swiper {
			height: 100%;
		}

		.image-wrapper {
			width: 100%;
			height: 100%;
		}

		.swiper-item {
			display: flex;
			justify-content: center;
			align-content: center;
			height: 750upx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
			}
		}

	}

	.title-section {
		padding: 20upx 30upx;
		.title {
			font-size: 32upx;height: 50upx;line-height: 50upx;
		}
		.price-box {
			align-items: baseline;height: 64upx;padding: 10upx 0;font-size: 26upx;
		}
		.price {
			font-size: 32upx + 2upx;
		}
		.m-price {
			margin: 0 12upx;color: #909399;text-decoration: line-through;
		}
	}

	.remark-section {
		margin-top: 16upx;margin-bottom:150rpx;
		.cu-item.cur{
			background: #ffffff;color: red;border-top: 4rpx solid;border-bottom: 0 !important;padding: 0;margin: 0;
		}
		swiper{
			min-height: 500rpx;
			.remark-content{
				margin:20rpx;
			}
		}
	}
	.cu-bar.fixed, .nav.fixed{
		bottom:0;top:unset !important;
	}
	.attr-content {
		padding: 10upx 30upx;
		.a-t {
			display: flex;
			image {
				width: 170upx;height: 170upx;flex-shrink: 0;border-radius: 8upx;
			}
			.right {
				display: flex;flex-direction: column;padding-left: 24upx;font-size: 24upx + 2upx;color: #606266;line-height: 42upx;
				.price {
					font-size: 32upx;margin-bottom: 10upx;
				}
				.selected-text {
					margin-right: 10upx;
				}
			}
		}
		.attr-list {
			display: flex;flex-direction: column;font-size: 28upx + 2upx;color: #606266;padding-top: 30upx;padding-left: 10upx;
		}
		.item-list {
			padding: 30upx 0 0;display: flex;flex-wrap: wrap;
			text {
				display: flex;align-items: center;justify-content: center;background: #eee;margin-right: 20upx;margin-bottom: 20upx;border-radius: 100upx;min-width: 60upx;height: 60upx;padding: 0 20upx;font-size: 28upx;color: #303133;
			}
			.selected {
				background: #fbebee;color: $uni-color-primary;
			}
		}
	}
	.coupon-list{
		max-height: 620rpx;overflow: auto;
		.coupon-item {
			display: flex;flex-direction: column;margin: 20upx 24upx;background: #fff;text-align: left;
			.con {
				display: flex;align-items: center;position: relative;height: 120upx;padding: 0 30upx;
				&:after {
					position: absolute;left: 0;bottom: 0;content: '';width: 100%;height: 0;border-bottom: 1px dashed #f3f3f3;transform: scaleY(50%);
				}
			}
			.left {display: flex;flex-direction: column;justify-content: center;flex: 1;overflow: hidden;height: 100upx;}
			.title {font-size: 32upx;color: #303133;margin-bottom: 10upx;}
			.time {font-size: 24upx;color: #909399;}
			.right {display: flex;flex-direction: column;justify-content: center;align-items: center;font-size: 26upx;color: #606266;height: 100upx;}
			.price {
				font-size: 44upx;color: #fa436a;
				&:before {
					content: '￥';
					font-size: 34upx;
				}
			}
			.tips {
				font-size: 24upx;color: #909399;line-height: 60upx;padding-left: 30upx;
			}
			.circle {
				position: absolute;left: -6upx;bottom: -10upx;z-index: 10;width: 20upx;height: 20upx;background: #f3f3f3;border-radius: 100px;
				&.r {
					left: auto;right: -6upx;
				}
			}
		}
	}
	.no_coupon{margin: 20% 0;}
</style>